/**
 * Created by chocolate on 16/5/27.
 */

import React, {
  Component,
  StyleSheet,
  Text,
  TextInput,
  View,
  TabBarIOS,
  ListView,
  Image,
} from 'react-native';

var Title = require('./Title');

var query = require('./Query').query;
import Calendar from 'react-native-calendar';
import SegmentedView from 'react-native-segmented-view';

var ChineseNumber = ['零','一','二','三','四','五','六','七','八','九'];

class Course extends Component{
  constructor(props){
    super(props);
    this.ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.childList = this.props.childList;
    this.courseList = [];                                       //从服务器获取的course列表
    this.state = {
      childNames:this._getChildNameArray(this.childList),       //作为segment的数据源      
      selectedIndex:0,                                          //SegmentedControlIOS的默认选项页
      selectedDate:new Date(),
      parent:this.props.user,                                   //当前家长对象(从login模块传递过来的)
      dataSource:this.ds.cloneWithRows([])                      //ListView的数据源
    }
  }

  /**
   * 组件加载成功回调函数
   */
  componentDidMount(){
    this._refreshCourseList(this.state.selectedDate);
  }

  /**
   * 根据上层模块传入的孩子列表，获取孩子姓名字符串数组，
   *  主要是为了用来更新segment
   */
  _getChildNameArray(childList){
    var childNameList = [];
    childList.forEach((item, index, array) =>{
      childNameList.push(item.name);
    })
    return childNameList;
  }

  /**
   * 根据选择的日期和学生，请求并刷新课程表
   */
  _refreshCourseList(date){
    this.courseList = [];
    console.log("查询学生"+this.childList[this.state.selectedIndex].id+"在"+date+"的课程表");
    console.log("这天是周"+date.getDay());
    // query.getCourse(this.childList[this.state.selectedIndex].id,date.getDay(),this,function(owner,response){
    //   if(response.success === true){
    //     owner.courseList = response.message;
    //     owner._updateListView();}})
    storage.load({
      key:'course',
      id:this.childList[this.state.selectedIndex].id,
      syncInBackground: false,
    }).then(ret=>{
      this.courseList = ret[date.getDay()];
      this._updateListView();
    }).catch(err => {
      console.warn(err);
    })
  }

  /**
   * 刷新LisView
   */
  _updateListView(){
    this.setState({dataSource:this.ds.cloneWithRows(this.courseList)});
  }

  /**
   * 点击返回按钮,返回上层界面
   * @private
   */
  _onPressReturn(){
    this.props.navigator.pop();
  }


  /**
   * 渲染孩子事件列表的每一行数据
   * @param rowData
   * @param sectionID
   * @param rowID
   * @returns {XML}
   */
  renderCourseRecord(rowData: string,sectionID: number, rowID: number){
    //在抱抱界面看到的是当天的事件数据,因此不需要日期,只需要时间
    return (
      <View style={styles.row}>
        <Text style={styles.text}>第{ChineseNumber[rowData.seqNo]}节</Text>
        <Text style={styles.text}>{rowData.startTime}-{rowData.endTime}</Text>
        <View style={{width:40}}/>
        <Text style={styles.text}>{rowData.name}</Text>
      </View>)

  }

  /**
   * 切换日期,会触发重新刷新课程表
   */
  _onDateSelect(datestr){
    console.log(typeof (datestr));

    //将字符串转化为date类型(2016-06-06T00:00:00+08:00)
    var year = datestr.substr(0,4);
    var month = datestr.substr(5,2);
    var day = datestr.substr(8,2);
    var date = new Date();
    date.setFullYear(year);
    date.setMonth(month-1);
    date.setDate(day);
    console.log("转换后的日期对象："+date.toString());
    this.setState({selectedDate:date});
    this._refreshCourseList(date);

  }

  
  /**
   * 点击SegmentBar更换学生,会触发重新刷新课程表
   */
  _onPressSegment(index){
    this.setState({selectedIndex: index});
    console.log("切换Segment,当前所选择的index:"+index);
    this._refreshCourseList(this.state.selectedDate);
  }

  render(){

    return(

          <View style={styles.container}>
            <Title title={{center:"课程表",left:"返回",leftAct:this._onPressReturn.bind(this)}}></Title>

              <SegmentedView
                titles={this.state.childNames}
                index={this.state.selectedIndex}
                stretch={true}
                barPosition={'bottom'}
                onPress={this._onPressSegment.bind(this)}
                style={{flex:0}}/>


             <Calendar
              scrollEnabled={true}              // False disables swiping. Default: True
              showControls={true}               // False hides prev/next buttons. Default: False
              titleFormat={'YYYY年MM月'}         // Format for displaying current month. Default: 'MMMM YYYY'
              dayHeadings={['日','一','二','三','四','五','六']}  // Default: ['S', 'M', 'T', 'W', 'T', 'F', 'S']
              prevButtonText={'上一月'}           // Text for previous button. Default: 'Prev'
              nextButtonText={'下一月'}           // Text for next button. Default: 'Next'
              onDateSelect={(date) => this._onDateSelect(date)} // Callback after date selection
              customStyle={{day: {fontSize: 15, textAlign: 'center'},
                    calendarContainer:{backgroundColor:'#FFF'},
                    controlButton:{backgroundColor:'#06a9fe'},
                    controlButtonText:{color:'#FFF'}}} // Customize any pre-defined styles
            />

            <View style={styles.course}>
              <Image source={require('../../icon/course.png')}/>
              <Text style={{marginLeft:5,color:'#2981b1',fontSize:14}}>课程表:</Text>
            </View>
            
            <Image style={{marginRight:20}} source={require('../../icon/course-back.png')}>
              <ListView dataSource={this.state.dataSource}
                        renderRow={this.renderCourseRecord}
                        enableEmptySections={true}
                        style={styles.listView} />
            </Image>            
          </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#eeeeee',
    flex: 1,
  },
  Title: {
    height: 40,
    marginTop: 20,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    borderColor: 'gray',
    borderTopWidth: 1,
    borderBottomWidth: 1,
  },
  course:{
    marginTop:5,
    marginLeft:30,
    flexDirection:'row',
    alignItems:'center'
  },
  listView: {
    marginTop:40,
    marginLeft:20,
    marginRight:20,
    alignSelf:'stretch',
    paddingTop: 5,
  },
  row:{
    flexDirection: 'row',
    justifyContent: 'center',
    padding: 5,
    backgroundColor: '#FFF',
    alignItems:'center',
    borderBottomWidth:1,
    borderStyle:'solid',
    borderColor:'#eeeeee',
    height:25,
  },
  text:{
    fontSize:14,
    width:100,
    color:'#707070',
    textAlign:'center',
  }

})

module.exports = Course;